package com.handong.handserialprogram.module.loginoutring;

import android.support.annotation.NonNull;
import android.view.View;

import com.handong.handserialprogram.R;
import com.handong.handserialprogram.model.entities.CriminalEntity;
import com.handong.handserialprogram.model.entities.FootRingNewEntity;
import com.handong.handserialprogram.model.status.FootRingStatus;
import com.handong.handserialprogram.model.status.RingResponse;
import com.handong.handserialprogram.module.base.BasePresenter;
import com.handong.handserialprogram.module.base.BaseView;
import com.handong.handserialprogram.module.serialport.SerialPortUtil;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.EventBusUtil;
import com.handong.handserialprogram.utils.FootRingNewUtil;
import com.handong.handserialprogram.utils.SPUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created by zhongqiu on 2020/2/11.
 */

public class LoginOutRingPresenter extends BasePresenter<LoginOutRingActivity> {

    private SerialPortUtil mSerialPortUtil;
    private CopyOnWriteArrayList<FootRingNewEntity> logoutFR;
    private CopyOnWriteArrayList<FootRingNewEntity> mList;
    private Vector<CriminalEntity> mCriminalList;

    public LoginOutRingPresenter(BaseView view) {
        super(view);
        init();
        logoutFR=new CopyOnWriteArrayList<>();
        mCriminalList=new Vector<>();
        mList=new CopyOnWriteArrayList<>();
    }

    protected void init(){
        EventBusUtil.register(this);
        mSerialPortUtil = SerialPortUtil.getInstance(mView);
        mSerialPortUtil.openSerialPortToReadData();
        mSerialPortUtil.SetReadRunnableIsStop(true);
        mSerialPortUtil.updateWorking(false);
        setRemindSound(false);
    }

    @Override
    protected void exit() {
        EventBusUtil.unRegister(this);
        if (this.mSerialPortUtil != null) {
            this.mSerialPortUtil.closeUploadData();
            this.mSerialPortUtil.closeSerialPort();
        }
        super.exit();
    }

//    protected void LoginOut(String RingId)
//    {
//        this.mView.showLoadDialog("正在休眠脚环："+RingId);
//        mSerialPortUtil.logoutFootRing(RingId);
//
//    }

    @Subscribe(priority = 100, threadMode = ThreadMode.MAIN)
    public void receiveRingResponse(RingResponse response) {

        switch (response.getResponseCode()) {
            case RingResponse.LOGOUT_ORDER://休眠脚环
                if (response.isSuccess()) {
                    mView.dismissLoadingDialog();
                    logoutSuccess();
//                    if(!logoutFR.isEmpty()){
//                        FootRingNewEntity result= FootRingNewUtil.findFootRingById(logoutFR,response.getRingID());
//                        if (result!=null) {
//                            if (!result.isDelete())  {
//                                //synchronized (logoutFR) {
//                                logoutFR.remove(result);
//                                //result.setDelete(true);
//                                //mSendRunnable.setmRingList(logoutFR);
//                                logoutAllFootRing();
//
//                                if (logoutFR.isEmpty()) {
//                                    mView.dismissLoadingDialog();
//                                    logoutSuccess();
//                                }
//                                // }
//                            }
//                        }
//
//                        break;
//                    }else{
//                        mView.dismissLoadingDialog();
//                        logoutSuccess();
//                    }
                } else {
//                    for (FootRingNewEntity entity :
//                            logoutFR) {
//                        entity.setDelete(false);
//                    }
                    //mSendRunnable.setmRingList(logoutFR);
                    mView.dismissLoadingDialog();
                    mView.logoutFootRingError(response.getRingID());
                }

                break;


            default:
                return;
        }
    }

    /**
     * 恢复当前第一个脚环
     */
    public void resumeCurrentFootRing(){
        if(!logoutFR.isEmpty()&&mSerialPortUtil!=null){
            String ringId=logoutFR.get(0).getRingID();
            //this.mView.showLoadDialog("正在休眠脚环："+ringId);
            this.mSerialPortUtil.resumeFootRing(ringId);
        }
    }

    /**
     * 强制退出
     */
    protected void logoutSuccess(){

        for (CriminalEntity criminalEntity:mCriminalList) {
            criminalEntity.setRingEntity(null);
        }
        mView.finish();
    }

    /**
     *休眠全部脚环
     */
    public void  logoutAllFootRing() {
        if(!logoutFR.isEmpty()&&mSerialPortUtil!=null){
            logoutFR.get(0).setLoginOutAlarm(true);
            this.mView.showLoadDialog("正在休眠脚环...");
            this.mSerialPortUtil.mSendRunnable.DelayTime=100;
            this.mSerialPortUtil.mSendRunnable.isLoginOut=true;


        }
        else{
                AppUtil.showShortToast(mView, "注销成功！");
        }
    }

    /**
     * 判断当前是否有任何罪犯逃脱
     * @return
     */
    protected boolean checkIsAnyCriminalEscape()
    {
        for (FootRingNewEntity entity:
                logoutFR) {
            if (entity.isSignlarWeek()||SPUtil.getIntValue(SPUtil.STOP_MISSION_SET_DISTANCE)<=entity.getActualRingDistance()||!entity.isResponseDistance())
            {
                return true;
            }
        }
        return false;
    }

    protected void CreateCriminal()
    {
        mView.setCenterTitle("注销脚环");
        mSerialPortUtil.mBindedRingList.clear();
        String[] RingIdList;
        if(mView.RingId.contains(";"))
        {
            RingIdList=mView.RingId.split(";");

        }
        else{
            RingIdList=new String[1];
            RingIdList[0]=mView.RingId;

        }

        List<String> list = new ArrayList<String>();
        for (int i=0; i<RingIdList.length; i++) {
            if(!list.contains(RingIdList[i])) {
                list.add(RingIdList[i]);
            }
        }

        for(int j = 0;j<list.size();j++){
            if (!(list.get(j)==null)){
                //isHasBinding=true;
                mSerialPortUtil.mBindedRingList.add(list.get(j));
                CriminalEntity criminalEntity=new CriminalEntity();
                FootRingNewEntity entity=new FootRingNewEntity();
                entity.setRingID(list.get(j));
                entity.setMyBingding(false);
                entity.setActualRingDistance(0f);
                entity.setWork(true);
                entity.setIsActive(32);

                criminalEntity.setEquipmentId(entity.getRingID());
                criminalEntity.setRingEntity(entity);
                mCriminalList.add(criminalEntity);
                mList.add(entity);
            }
        }

        mSerialPortUtil.setRingList(mList);
        mSerialPortUtil.setSendStart();
        mView.showCriminalList(mCriminalList);
    }


    /**
     * 是否开启报警提示。
     */
    public void setRemindSound(boolean paramBoolean) {
        this.mSerialPortUtil.setPlaySound(paramBoolean);
    }





    /**
     * 获取脚环数据
     */
    @Subscribe(priority = 100, threadMode = ThreadMode.MAIN)
    public void receiveFootRingList(CopyOnWriteArrayList<FootRingNewEntity> list) {
//        if ( mView == null || !mView.isResume()) {//mIndex == -1 ||
//            return;
//        }

        if ( mView == null ) {//mIndex == -1 ||
            return;
        }

        /**
         * 恢复脚环监听
         */
        if(mCriminalList!=null&&!mCriminalList.isEmpty()){
            for (CriminalEntity criminalEntity:mCriminalList) {
                for (FootRingNewEntity  footRingEntity:list) {
                    if(criminalEntity.getRingEntity()==null
                            &&criminalEntity.getEquipmentId()!=null
                            &&criminalEntity.getEquipmentId().equals(footRingEntity.getRingID())
                            &&footRingEntity.isMyBingding()){
                        criminalEntity.setRingEntity(footRingEntity);
                    }
                }
            }
        }


        logoutFR.clear();
        for (FootRingNewEntity entity:list) {
            if(entity.isMyBingding()){
                logoutFR.add(entity);
            }
        }
        //mSendRunnable.setmRingList(logoutFR);

        for (FootRingNewEntity footRingEntity:list) {
            for (int i=0;i<mCriminalList.size();i++){
                CriminalEntity entity= mCriminalList.get(i);
                if(entity.getRingEntity()!=null&&entity.getRingEntity().getRingID().equals(footRingEntity.getRingID())){
                    entity.setRingEntity(footRingEntity);
                    mView.refreshRingDistance(i);//更新item

                }
            }
        }
    }
}
